﻿using System;
using System.Collections.Generic;
using System.IO;
using NAudio.Wave;

namespace Coding4Fun.BoxingBots.Common
{
	public class AudioPlayer
	{
		static readonly Dictionary<SoundCue, WaveItem> SoundMap = new Dictionary<SoundCue, WaveItem>();

		public static void PlayCue(SoundCue cue)
		{
			if(SoundMap.ContainsKey(cue))
			{
				WaveItem wi = SoundMap[cue];
				wi.WaveChannel32.Seek(0, SeekOrigin.Begin);
				wi.WaveOut.Play();
			}
			else
			{
				string path = "./Audio/";

				switch(cue)
				{
					case SoundCue.Punch:
						path = Path.Combine(path, "punch.wav");
						break;
					case SoundCue.Hit:
						path = Path.Combine(path, "hit.wav");
						break;
					default:
						throw new ArgumentOutOfRangeException("cue");
				}

				WaveStream waveStream = new WaveFileReader(path);
				WaveChannel32 stream = new WaveChannel32(waveStream);
				WaveOut wo = new WaveOut();
				wo.Init(stream);
				wo.Play();

				SoundMap[cue] = new WaveItem { WaveOut = wo, WaveChannel32 = stream };
			}
		}

		public static void StopCue(SoundCue cue)
		{
			if(SoundMap.ContainsKey(cue))
				SoundMap[cue].WaveOut.Stop();
		}

		public static void StopAll()
		{
			foreach(WaveItem wi in SoundMap.Values)
				wi.WaveOut.Stop();
		}

		public static void Shutdown()
		{
			foreach(WaveItem wi in SoundMap.Values)
			{
				wi.WaveOut.Stop();
				wi.WaveOut.Dispose();
			}
		}
	}
}
